<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="数据年份" prop="dataYear">
        <el-select v-model="queryParams.dataYear" placeholder="请选择年份" clearable>
          <el-option
            v-for="item in yearOptions"
            :key="item.dataYear"
            :label="item.dataYear"
            :value="item.dataYear"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="指标级别" prop="indeLevel">
        <el-select v-model="queryParams.indeLevel" placeholder="请选择指标级别" clearable >
          <el-option
            v-for="dict in dict.type.yc_organ_level"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="指标名称" prop="indeId">
        <el-select v-model="queryParams.indeId" filterable placeholder="请选择指标" clearable  size="small"
                   :disabled="indeChangeEnable">
          <el-option
            v-for="item in ycindeOptions"
            :key="item.indeId"
            :label="item.indeName"
            :value="item.indeId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="组织名称" prop="orgId">
        <el-select v-model="queryParams.orgId" filterable placeholder="请选择组织" clearable  size="small">
          <el-option
            v-for="item in ycorgOptions"
            :key="item.orgId"
            :label="item.orgName"
            :value="item.orgId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="维度值" prop="dataDimension">
        <el-input
          v-model="queryParams.dataDimension"
          placeholder="请输入维度值"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="数据值" prop="dataValue">-->
<!--        <el-input-->
<!--          v-model="queryParams.dataValue"-->
<!--          placeholder="请输入数据值"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="维度" prop="dimension">
        <el-select v-model="queryParams.dimension" placeholder="请选择维度" clearable>
          <el-option
            v-for="dict in dict.type.you_dimension"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['system:data:add']"-->
<!--        >发布数据</el-button>-->
<!--      </el-col>-->

<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['system:data:add']"-->
<!--        >未达标数据</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['system:data:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['system:data:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->

<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="info"-->
<!--          plain-->
<!--          icon="el-icon-upload2"-->
<!--          size="mini"-->
<!--          @click="handleImport"-->
<!--          v-hasPermi="['system:data:import']"-->
<!--        >批量发布数据</el-button>-->
<!--      </el-col>-->

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:data:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="数据序号" align="center" prop="dataId" v-if="columns[0].visible"/>
      <el-table-column label="指标名称" align="center" prop="ycInde.indeName" v-if="columns[1].visible"/>
      <el-table-column label="部门id" align="center" prop="ycInde.deptId" v-if="columns[2].visible"/>
      <el-table-column label="组织名称" align="center" prop="ycOrg.orgName" v-if="columns[3].visible"/>
      <el-table-column label="填报部室" align="center" prop="ycInde.deptId" :formatter="formatDeptName" v-if="columns[11].visible"/>
      <el-table-column label="数据值" align="center" prop="dataValue" v-if="columns[4].visible"/>
      <el-table-column label="维度值" align="center" prop="dataDimension" v-if="columns[5].visible"/>

      <el-table-column label="维度" align="center" prop="dimension" v-if="columns[6].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.you_dimension" :value="scope.row.dimension"/>
        </template>
      </el-table-column>

      <el-table-column label="状态值" align="center" prop="status" v-if="columns[7].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.data_status1" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="数据年份" align="center" prop="dataYear" v-if="columns[8].visible"/>

      <el-table-column label="是否达标" align="center" prop="upToStandard" v-if="columns[9].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.up_to_standard" :value="scope.row.upToStandard"/>
        </template>
      </el-table-column>
      <el-table-column label="措施Id" align="center" prop="meaId" v-if="columns[10].visible"/>

<!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--        <template slot-scope="scope">-->

<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-hasPermi="['system:data:edit']"-->
<!--          >修改</el-button>-->

<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['system:data:remove']"-->
<!--          >删除</el-button>-->

<!--        </template>-->
<!--      </el-table-column>-->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改油厂数据管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="指标名称" prop="indeId">
          <el-select v-model="form.indeId" filterable placeholder="请选择指标" clearable  >
            <el-option
              v-for="item in ycindeOptions"
              :key="item.indeId"
              :label="item.indeName"
              :value="item.indeId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="组织序号" prop="orgId">
          <el-select v-model="form.orgId" filterable placeholder="请选择组织" clearable  >
            <el-option
              v-for="item in ycorgOptions"
              :key="item.orgId"
              :label="item.orgName"
              :value="item.orgId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="维度值" prop="dataDimension" >
          <el-input style="width: 220px" v-model="form.dataDimension" placeholder="请输入维度值"  />
        </el-form-item>
<!--        <el-form-item label="数据值" prop="dataValue">-->
<!--          <el-input v-model="form.dataValue" placeholder="请输入数据值" />-->
<!--        </el-form-item>-->

        <el-form-item label="维度" prop="dimension">
          <el-select v-model="form.dimension" placeholder="请选择维度">
            <el-option
              v-for="dict in dict.type.you_dimension"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="数据年份" prop="dataYear" >
          <el-input style="width: 220px" v-model="form.dataYear" placeholder="请输入数据年份" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {listData, listDataMore, getData, delData, addData, updateData, ycdatayearSelect} from "@/api/system/data";
import {ycindeSelect} from "@/api/system/inde";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {ycorgSelect} from "@/api/system/org";
import {getUserProfile} from "@/api/system/user";
import {getToken} from "@/utils/auth";
import {DeptSelect} from "@/api/system/dept";


export default {
  name: "Data",
  dicts:['you_dimension','data_status1','yc_organ_level','up_to_standard'],
  components:{ Treeselect },
  data() {
    return {
      currentYearNum:null,
      currentIndeLevelNum:null,
      //指标能否选择
      indeChangeEnable:true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      //指标下拉选项
      ycindeOptions: [],
      ycdeptOptions:[],
      //组织下拉选项
      ycorgOptions:[],
      //年份选项
      yearOptions:[],
      // 总条数
      total: 0,
      // 油厂数据管理表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/data/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        indeId: null,
        orgId: null,
        indeLevel:null,
        dataDimension: null,
        dataValue: null,
        dimension: null,
        status: null,
        dataYear: null,
        deptId:null
      },
      //列信息
      columns:[
        {key:0,label:`数据序号`,visible:false},
        {key:1,label:`指标名称`,visible:true},
        {key:2,label:`部门id`,visible:false},
        {key:3,label:`组织名称`,visible:true},
        {key:4,label:`数据值`,visible:true},
        {key:5,label:`纬度值`,visible:true},
        {key:6,label:`维度`,visible:true},
        {key:7,label:`状态值`,visible:true},
        {key:8,label:`数据年份`,visible:true},
        {key:9,label: `是否达标`,visible: true},
        {key:10,label: `措施Id`,visible: false},
        {key:11,label: `填报部室`,visible: true},
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },

    };
  },
  created() {
    this.getList();
    this.getYcIndeSelect();
    this.getYcOrgSelect();
    this.getDataYear();
    this.getYcDeptSelect();
  },
  watch:{
    'queryParams.dataYear':{
      deep:true,
      handler(newVaule, oldValue){
        this.currentYearNum = null;
        this.currentYearNum = newVaule;
        console.log("currentYearNum is",this.currentYearNum)
        this.getIndeSelect(this.currentIndeLevelNum)
      }
    },
    'queryParams.indeLevel':{
      deep:true,
      handler(newVaule, oldValue){
        this.currentIndeLevelNum = null;
        this.currentIndeLevelNum = newVaule;
        console.log("currentIndeLevelNum is",this.currentIndeLevelNum)
        this.getIndeSelect(this.currentIndeLevelNum)
      }
    },
  },
  methods: {
    formatDeptName(row){
      for(let i = 0; i < this.ycdeptOptions.length; i++){
        if(this.ycdeptOptions[i].deptId == row.ycInde.deptId){
          return this.ycdeptOptions[i].deptName
        }
      }
    },
    //获取部门下拉选项
    getYcDeptSelect(){
      DeptSelect().then(response =>{
        var deptOptions = [];
        this.ycdeptOptions = response.data;
        deptOptions = this.ycdeptOptions.splice(0, 3)
        console.log("this.ycdeptOptions",this.ycdeptOptions);
      })
    },
    getIndeSelect(currentIndeLevel){
      this.ycindeOptions = []
      ycindeSelect().then(response =>{
        var tem_ycindeOptions = response.data;
        console.log(tem_ycindeOptions)
        this.indeChangeEnable = true;
        for (let i in tem_ycindeOptions){
          if(this.currentYearNum == tem_ycindeOptions[i].indeYear && currentIndeLevel == tem_ycindeOptions[i].indeLevel){
            this.ycindeOptions.push(tem_ycindeOptions[i]);
            this.indeChangeEnable = false;
          }
          else continue;
        }
      })
    },

    /** 查询油厂数据管理列表 */
    // getList() {
    //   this.loading = true;
    //   let deptId;
    //   getUserProfile().then(response => {
    //     if (response.roleGroup != "超级管理员") {
    //       deptId = response.data.deptId;
    //       console.log(deptId)
    //       listData(this.queryParams).then(response => {
    //         this.tempList = response.rows;
    //         console.log(this.tempList)
    //         this.dataList=[];
    //         this.total=0;
    //         let num = 0;
    //         for (let i = 0; i < 10; i++) {
    //           if (this.tempList[i].ycInde.deptId == deptId) {
    //             this.dataList.push(this.tempList[i]);
    //             num++;
    //           }
    //         }
    //         this.total = num;
    //         this.loading = false;
    //       });
    //     }else{
    //       listData(this.queryParams).then(response => {
    //         this.dataList = response.rows;
    //         this.total = response.total;
    //         this.loading = false;
    //       });
    //     }
    //   });
    // },
    /** 查询油厂数据管理列表 */
    getList() {
      this.loading = true;
      let deptId;
      getUserProfile().then(response => {
        if (response.roleGroup != "超级管理员") {
          deptId = response.data.deptId;
          console.log(deptId)
          this.queryParams.deptId = deptId;
          listDataMore(this.queryParams).then(response => {
            this.dataList = response.rows;
            this.total = response.total;
            this.loading = false;
          });
        }else{
          listDataMore(this.queryParams).then(response => {
            this.dataList = response.rows;
            this.total = response.total;
            this.loading = false;
          });
        }
      });
    },
    //获取年份
    getDataYear(){
      ycdatayearSelect().then(response =>{
        this.yearOptions = response.data;
      })
    },
    //获取指标下拉选项
    getYcIndeSelect(){
      ycindeSelect().then(response=>{
        this.ycindeOptions = response.data;
      })
    },
    //获取组织下拉选项
    getYcOrgSelect(){
     ycorgSelect().then(response =>{
       this.ycorgOptions = response.data;
     })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        dataId: null,
        indeId: null,
        orgId: null,
        dataDimension: null,
        indeLevel:null,
        dataValue: null,
        createTime: null,
        dimension: null,
        status: 0,
        dataYear: null
      };
      this.indeChangeEnable = true
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
     handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dataId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加油厂数据管理";
      // listData().then(response=>{
      //   this.ycorgOption = [];
      //   const data = {orgId: 0,orgName:'顶级节点', children:[]};
      //   data.children = this.handleTree(response.data,"ycOrg.orgId","ycOrg.parentId");
      //   this.ycorgOption.push(data);
      // });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const dataId = row.dataId || this.ids
      getData(dataId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改油厂数据管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.dataId != null) {
            updateData(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addData(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dataIds = row.dataId || this.ids;
      this.$modal.confirm('是否确认删除油厂数据管理编号为"' + dataIds + '"的数据项？').then(function() {
        return delData(dataIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      let deptId;
      getUserProfile().then(response => {
        if (response.roleGroup != "超级管理员") {
          deptId = response.data.deptId;
          this.queryParams.deptId = deptId;
          this.download('system/data/export', {
            ...this.queryParams
          }, `data_${new Date().getTime()}.xlsx`)
        }else{
          this.download('system/data/export', {
            ...this.queryParams
          }, `data_${new Date().getTime()}.xlsx`)
        }
      });
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "指标导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/data/importTemplate', {
      }, `data_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
